package com.atguigu.gmall.realtime.app.dwd.db;

import com.atguigu.gmall.realtime.app.BaseSQLApp;
import com.atguigu.gmall.realtime.util.SQLUtil;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @Author lzc
 * @Date 2022/5/2 8:23
 */
public class DWD_14_DwdInteractionFavorAddApp extends BaseSQLApp {
    public static void main(String[] args) {
        new DWD_14_DwdInteractionFavorAddApp()
            .init("DwdInteractionFavorAddApp", 3014, 1, "DwdInteractionFavorAddApp");
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       StreamTableEnvironment tEnv) {
        /*
            数据是新增
         */
        // TODO 3. 从 Kafka 读取业务数据，封装为 Flink SQL 表
        tEnv.executeSql(
            "create table topic_db(" +
                "`database` string, " +
                "`table` string, " +
                "`type` string, " +
                "`data` map<string, string>, " +
                "`ts` string " +
                ")" + SQLUtil.getKafkaDDL("dwd_interaction_favor_add", "ods_db"));
        
        // TODO 4. 读取收藏表数据
        Table favorInfo = tEnv.sqlQuery(
            "select " +
                "data['id'] id, " +
                "data['user_id'] user_id, " +
                "data['sku_id'] sku_id, " +
                "date_format(data['create_time'],'yyyy-MM-dd') date_id, " +
                "data['create_time'] create_time, " +
                "ts " +
                "from topic_db " +
                "where `table` = 'favor_info' " +
                "and `type` = 'insert' ");
        tEnv.createTemporaryView("favor_info", favorInfo);
        
        // TODO 5. 创建 Upsert-Kafka dwd_interaction_favor_add 表
        tEnv.executeSql(
            "create table dwd_interaction_favor_add ( " +
                "id string, " +
                "user_id string, " +
                "sku_id string, " +
                "date_id string, " +
                "create_time string, " +
                "ts string, " +
                "primary key(id) not enforced " +
                ")" + SQLUtil.getUpsertKafkaDDL("dwd_interaction_favor_add"));
        
        // TODO 6. 将数据写入 Upsert-Kafka 表
        tEnv.executeSql(
            "insert into dwd_interaction_favor_add select * from favor_info");
    }
}
